<template>
	<view class="page" style="padding-bottom: 180rpx;">
		<topVue title="邀请海报"></topVue>
		
		<view class="posterVue margin0">
			<swiper class="swiper" @change="change" circular :current="current" :indicator-dots="true" :autoplay="false">
				<swiper-item class="relative">
					<canvas
						:style="{ width: cansWidth + 'px', height: cansHeight + 'px'}"
						style="margin: 0 auto;"
						class="absolute-auto"
						canvas-id="canvasId0"
					></canvas>
				</swiper-item>
				<!-- <swiper-item class="relative">
					<canvas
						:style="{ width: cansWidth + 'px', height: cansHeight + 'px'}"
						style="margin: 0 auto;"
						class="absolute-auto"
						canvas-id="canvasId1"
					></canvas>
				</swiper-item> -->
				<!-- 
				<swiper-item class="relative">
					<canvas
						:style="{ width: cansWidth + 'px', height: cansHeight + 'px'}"
						style="margin: 0 auto;"
						class="absolute-auto"
						canvas-id="canvasId2"
					></canvas>
				</swiper-item> -->
			</swiper>
			
		</view>
		
		<view class="botVue flex align-center padding-row30">
			<view class="flex-column align-center w33" @click="shareByWeChat()">
				<image src="../../static/person/share_1.png" style="width: 66rpx; height: 66rpx; margin-bottom: 20rpx;"></image>
				<text>微信</text>
			</view>
			<view class="flex-column align-center w33" @click="shareByCircle()">
				<image src="../../static/person/share_2.png" style="width: 66rpx; height: 66rpx; margin-bottom: 20rpx;"></image>
				<text>朋友圈</text>
			</view>
			<view class="flex-column align-center w33" @click="saveImageToPhotosAlbum()">
				<image src="../../static/person/share_3.png" style="width: 66rpx; height: 66rpx; margin-bottom: 20rpx;"></image>
				<text>保存到本地</text>
			</view>
		</view>
	</view>
</template>

<script>
	import QR from "@/common/qrcode/qrcode.js";
	import baseUrl from "@/common/url.js"
	import { mapState } from "vuex"
	export default {
		data(){
			return {
				cansWidth: 0, //海报宽度
				cansHeight: 0,
				poster:['../../static/poster2.jpg'],
				current: 0,
			}
		},
		computed: {
			...mapState({
				user: state => state.user,
			})
		},
		mounted() {
			this.initCanvas()
		},
		methods: {
			change(e){
				this.current = e.detail.current
			},
			
			shareByWeChat(){
				let that = this
				uni.canvasToTempFilePath({
                    canvasId: `canvasId${that.current}`,
                    success: (res) => {
						var token = uni.getStorageSync('token');
						console.log(token)
						var files=[];
						console.log("11111", res.tempFilePath)
						files.push({'name':'file','uri':res.tempFilePath});
						uni.uploadFile({
							url:baseUrl.url + '/app-api/infra/file/upload', //仅为示例，非真实的接口地址
							files:files,
							formData: {
								file: res.tempFilePath,
								path: "after_sale/",
							},
							header: {
								"tenant-id": 162,
								Authorization: token,
							},
							success: (result) => {
								var data=JSON.parse(result.data);
								console.log("22222", data.data)
								uni.share({
									provider: "weixin",
									scene: "WXSceneSession",
									type: 2,
									imageUrl: data.data,
									success: function (RES) {
										console.log("success:" + JSON.stringify(RES));
									},
									fail: function (ERR) {
										console.log("fail:" + JSON.stringify(ERR));
									}
								});
							},
							fail(err) {	
								console.log(err)
							}
						})
                    },
                    fail: (err) => {
                        console.error('Canvas to temp file path failed', err);
                    }
                });	
			},
			
			shareByCircle(){
				let that = this
				uni.canvasToTempFilePath({
				    canvasId: `canvasId${that.current}`,
				    success: (res) => {
						var token = uni.getStorageSync('token');
						console.log(token)
						var files=[];
						console.log("11111", res.tempFilePath)
						files.push({'name':'file','uri':res.tempFilePath});
						uni.uploadFile({
							url:baseUrl.url + '/app-api/infra/file/upload', //仅为示例，非真实的接口地址
							files:files,
							formData: {
								file: res.tempFilePath,
								path: "after_sale/",
							},
							header: {
								"tenant-id": 162,
								Authorization: token,
							},
							success: (result) => {
								var data=JSON.parse(result.data);
								console.log("22222", data.data)
								uni.share({
									provider: "weixin",
									scene: "WXSceneTimeline",
									type: 2,
									imageUrl: data.data,
									success: function (RES) {
										console.log("success:" + JSON.stringify(RES));
									},
									fail: function (ERR) {
										console.log("fail:" + JSON.stringify(ERR));
									}
								});
							},
							fail(err) {	
								console.log(err)
							}
						})
				    },
				    fail: (err) => {
				        console.error('Canvas to temp file path failed', err);
				    }
				});	
			},
			
			initCanvas() { //绘制海报
				const shareUrl = `https://flsnfuylofsy.sealosbja.site?inviteCode=${this.user.id}`;
				const userId = this.user.id + ""
				const QRCODE = QR.createQrCodeImg(shareUrl, {
					size: parseInt(110) //二维码大小
				})
				const width = uni.getStorageSync("screenWidth")
				this.cansWidth = width
				this.cansHeight = width * 1.388605
				console.log(this.cansWidth, this.cansHeight)
				uni.showLoading()
				let that = this;
				
				this.poster.forEach((item, index)=>{
					var context = uni.createCanvasContext(`canvasId${index}`)
					setTimeout(function() { //定时器，海报方法不能立即执行，等页面渲染完成
						context.drawImage(item, 0, 0, that.cansWidth, that.cansHeight) //个人信息背景
						context.drawImage(QRCODE, 45, 327, 100, 100)
						
						context.setFillStyle('#fff')
						context.setFontSize(13)
						context.fillText(that.user.nickname, 98, 155)
						context.fill()
						
						context.save()
						context.beginPath();
						context.arc(70, 150, 20, 0, 2 * Math.PI);
						context.closePath();
						context.clip(); // 裁剪路径内的区域
						context.drawImage(that.user.avatar, 50, 130, 40, 40);
					
						context.restore()
						uni.hideLoading()
						context.draw(false, ()=>{
							console.log("完毕")
						})
					}, 200);
				})
				
			},
			
			//保存海报
			saveImageToPhotosAlbum(e) { 
				let that = this;
				uni.showLoading();
				let tempRatio = 1.5;
				// #ifdef H5 || APP-PLUS
				tempRatio = 1;
				// #endif
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: that.cansWidth * tempRatio,
					height: that.cansHeight * tempRatio,
					destWidth: that.cansWidth * tempRatio * 2,
					destHeight: that.cansHeight * tempRatio * 2,
					canvasId: `canvasId${that.current}`,
					success: function(res) {
						uni.hideLoading()
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function(res) {
								uni.showToast({
									title: '保存相册成功',
									icon: "none"
								})
							},
							fail(res) {
								if (res.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
									uni.showModal({
										title: '您需要授权相册权限',
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success(res) {
													},
													fail(res) {
														console.log(res)
													}
												})
											}
										}
									})
								}
							}
						});
					},
					fail(res) {
						uni.hideLoading()
					}
				}, this)
			},
		}
	}
</script>

<style lang="less" scoped>
	.posterVue {
		width: 100%;
		height: calc(100vh - var(--status-bar-height) - 92rpx - 180rpx);
		.swiper {
			width: 100%;
			height: calc(100vh - var(--status-bar-height) - 92rpx - 180rpx);
		}
	}
	.botVue {
		width: 100%;
		height: 180rpx;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 99;
		background: #fff;
		text {
			line-height: 1;
			color: #4B5563;
		}
	}
</style>